/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.config;

import lombok.Cleanup;
import lombok.NoArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.jrose.core.util.CollectionUtils;
import org.jrose.core.util.JsonUtils;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@NoArgsConstructor
public class FileSystemAutoScanConfigManagerImpl extends ConfigManagerImpl {
    @Override
    protected Map<String, Object> doLoadResource(Resource resource) throws Exception {
        try {
            File baseFile = resource.getFile();
            String filename = resource.getFilename();
            return loadResourceFromFileSystem(baseFile, filename);
        } catch (FileNotFoundException ex) {
            log.warn("The resource to be loaded is not in file system, ignore auto scanning");
            return super.doLoadResource(resource);
        }
    }

    private Map<String, Object> loadResourceFromFileSystem(File baseFile, String filename) throws Exception {
        List<File> candidates = new LinkedList<>();

        File dir = baseFile.getParentFile();
        while (dir != null && dir.isDirectory()) {
            File file = new File(dir.getPath() + File.separator + filename);
            if (file.exists()) {
                candidates.add(file);
            }
            dir = dir.getParentFile();
        }

        Collections.reverse(candidates);

        File first = CollectionUtils.firstElement(candidates);
        @Cleanup InputStream inStream = new FileInputStream(first);
        String content = IOUtils.toString(inStream, "UTF-8");
        Map<String, Object> map = JsonUtils.fromJson(content);
        log.info("Load from '{}'...", first.getPath());

        for (int i = 1; i < candidates.size(); i++) {
            File candidate = candidates.get(i);
            @Cleanup InputStream is = new FileInputStream(candidate);
            content = IOUtils.toString(is, "UTF-8");
            Map<String, Object> each = new LinkedHashMap<>(JsonUtils.fromJson(content));

            Map commonPart = (Map) each.remove("commonConfig");
            map.putAll(each);

            if (commonPart != null) {
                if (map.containsKey("commonConfig")) {
                    //noinspection unchecked
                    ((Map) map.get("commonConfig")).putAll(commonPart);
                } else {
                    map.put("commonConfig", commonPart);
                }
            }
            log.info("Load from '{}'...", candidate.getPath());
        }

        log.info("[{}] dataSourceConfig", map.containsKey("dataSourceConfig") ? "v" : "x");
        log.info("[{}] mongoConfig", map.containsKey("mongoConfig") ? "v" : "x");
        log.info("[{}] memcachedConfig", map.containsKey("memcachedConfig") ? "v" : "x");
        log.info("[{}] commonConfig", map.containsKey("commonConfig") ? "v" : "x");

        return map;
    }
}
